package com.heima.common.exception;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Configuration
@RestControllerAdvice
@Slf4j
public class ExceptionCatch {

    @ExceptionHandler(Exception.class)
    public ResponseResult exception(Exception ex) {
        /*将错误信息记录在日志上*/
        log.error("Exception ex {}", ex);

        /*返回给用户有好的提示信息*/
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "您的网络异常请稍后再试");
    }
    @ExceptionHandler(CustomException.class)
    public ResponseResult custException(CustomException ex){
        /*将错误信息记录在日志上*/
        log.error("Exception ex {}",ex);

        /*返回给用户有好的提示信息*/
        return ResponseResult.errorResult(ex.getAppHttpCodeEnum());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult custMethodException(MethodArgumentNotValidException ex){
        /*将错误信息记录在日志上*/
        log.error("Exception ex {}",ex);
        ex.printStackTrace();
        BindingResult result = ex.getBindingResult();
        String errorMessage = result.getFieldError().getDefaultMessage();
        /*返回给用户有好的提示信息*/
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,errorMessage);
    }



}
